package com.liuxing.javaSpringBoot.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebListener;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Created by IntelliJ IDEA.
 * @File LogDestroyListenner.java
 * @Auth liuxing
 * @Date 2021/8/23 09:32
 * @Email liuxing997@foxmail.com
 */
@WebListener
public class LogDestroyListener implements ServletContextListener {
    //类名.class
    private final static Logger LOGGER = LoggerFactory.getLogger(LogDestroyListener.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        LOGGER.debug("==== Init Context ====");

        File destFolder = new File("/log");
        if (destFolder==null || !destFolder.exists()){
            return;
        }
        //判断文件是否当前日期不是就删除
        DateTimeFormatter dtf =   DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String currentDate = dtf.format(LocalDateTime.now());
        File[] files = destFolder.listFiles();
        for (File file:files){
            String fileName = file.getName();
            if (!fileName.contains(currentDate)){
                file.delete();
            }
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        LOGGER.debug("==== Destroy Context ====");
    }
}
